import { Component, OnInit, EventEmitter } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { Observable } from "rxjs/Observable";
import { BehaviorSubject } from "rxjs/BehaviorSubject";
import cloneDeep from "lodash/fp/cloneDeep"

import { TableTab } from "../f10-shared/interface-shared";
import { scroll } from "../f10-shared/common-methods";
import { removeHMS, hasownproperty } from "../f10-shared/util";
import { F10Service } from "../service/f10.service"

@Component({
  templateUrl: "news.component.html",
  styleUrls: ["news.component.less"]
})

export class NewsComponent implements OnInit {
  timer = null;
  currentTab: string = 'sub-title-1';
  // 股票代码Observable
  routerParamsStream: Observable<any>;
  // 公告列表状态仓库
  annoState: any = {
    downLoad: false,
    symbol: '',
    currentType: '',
    annoTypeLists: ['all', '1001', '1002', '1008', '1009', 'financial', '1011'],
    annoTypeSource: [{
      data: [],
      type: 'all',
      page: 1,
      perPage: 30,
      isDone: false
    }, {
      data: [],
      type: '1001',
      page: 1,
      perPage: 30,
      isDone: false
    }, {
      data: [],
      type: '1002',
      page: 1,
      perPage: 30,
      isDone: false
    }, {
      data: [],
      type: '1008',
      page: 1,
      perPage: 30,
      isDone: false
    }, {
      data: [],
      type: '1009',
      page: 1,
      perPage: 30,
      isDone: false
    }, {
      data: [],
      type: 'financial',
      page: 1,
      perPage: 30,
      isDone: false
    }, {
      data: [],
      type: '1011',
      page: 1,
      perPage: 30,
      isDone: false
    }]
  }
  // 公司新闻列表状态仓库
  compNewsState: any = {
    downLoad: false,
    symbol: '',
    currentType: '',
    annoTypeLists: ['compNews'],
    annoTypeSource: [{
      data: [],
      type: 'compNews',
      page: 1,
      perPage: 30,
      isDone: false
    }]
  }

  subLists: TableTab[] = [
    // {
    //   label: "公告与股价联动",
    //   class: 'sub-title-0'
    // },
    {
      label: "公司新闻",
      class: 'sub-title-1'
    },
    {
      label: "公司公告",
      class: 'sub-title-2'
    },
    // {
    //   label: "行业新闻",
    //   class: 'sub-title-3'
    // }
  ]

  // 公司公告tab
  annoTab: TableTab[] = [
    {
      label: "全部公告",
      class: "all"
    },
    {
      label: "定期报告",
      class: "1001"
    },
    {
      label: "业绩预测报告",
      class: "1002"
    },
    {
      label: "股权变动公告",
      class: "1008"
    },
    {
      label: "重大事项",
      class: "1009"
    },
    {
      label: "财务报告",
      class: "financial"
    },
    {
      label: "董事会、监事会、股东大会公告",
      class: "1011"
    }
  ]
  // 默认推一次公告类型流
  annoTypeEmitter = new BehaviorSubject('all');
  annoLoadEmitter = new BehaviorSubject('first');
  // 公司新闻 => 类型与加载推流(公司新闻不分类型为了代码复用这里默认给一种)
  compNewsTypeEmittter = new BehaviorSubject('compNews');
  compNewsLoadEmittter = new BehaviorSubject('first');

  // 公告列表数据
  annoData: Observable<any>;
  // 公司新闻列表数据
  compNewsData: Observable<any>;

  constructor(
    private router: ActivatedRoute,
    private f10Service: F10Service
  ) { }

  ngOnInit() {
    console.log('%c news component is work', 'color:#0f0')
    // 获取股票代码
    this.routerParamsStream = this.router.parent.parent.params.map(params => params["id"]).filter(id => !!id).map(id => {
      let stock = {
        symbol: (<string>id).replace("_", ".")
      };
      return stock
    })
    // 订阅公司公告列表
    this.annoData = this.getLists(this.routerParamsStream, this.annoTypeEmitter, this.annoLoadEmitter, this.annoState, this.getAnnouncements.bind(this))

    // 订阅公司新闻列表
    this.compNewsData = this.getLists(this.routerParamsStream, this.compNewsTypeEmittter, this.compNewsLoadEmittter, this.compNewsState, this.getCompNews.bind(this))
    
  }

  tabToggle (event) {
    this.currentTab = event
    // 滚动逻辑取消
    // this.timer = scroll(`segment-container`, event, this.timer);
  }

  // 切换公司公告类型 => 推流一次
  annoToggle (event) {
    console.log('annoToggle', event)
    this.annoTypeEmitter.next(event)
  }
  // 获取公告列表
  getAnnouncements (state) {
    console.log('%c 开始请求数据', 'color: #0f0')
    let index = state.annoTypeLists.indexOf(state.currentType)
    return this.f10Service.getAnnouncements({
      symbol: state.symbol,
      category: state.currentType,
      page: state.annoTypeSource[index].page,
      perPage: state.annoTypeSource[index].perPage
    })
  }
  // 加载更多通告列表
  loadMoreAnno () {
    console.log('loadmoreAnno')
    let signal:any = {
      loadMore: true
    }
    this.annoLoadEmitter.next(signal)
  }
  // 获取公告详情链接
  getAnnouncementsPdf (id) {
    return this.f10Service.getAnnouncementsPdf(id)
  }
  // 获取公司新闻列表
  getCompNews (state) {
    console.log('%c 开始请求新闻列表数据', 'color: #0f0')
    let index = state.annoTypeLists.indexOf(state.currentType)
    return this.f10Service.getNews({
      symbol: state.symbol,
      page: state.annoTypeSource[index].page,
      perPage: state.annoTypeSource[index].perPage
    })
  }
  // 加载更多公司新闻列表
  loadMoreCompNews () {
    console.log('loadMoreCompNews')
    let signal:any = {
      loadMore: true
    }
    this.compNewsLoadEmittter.next(signal)
  }


  // 获取公司公告列表，新闻列表管道
  getLists (routerParamsStream: Observable<any>, typeEmitter, loadEmitter, rawState, loadData: Function) {
    let combineSymbolCategory = Observable.combineLatest(routerParamsStream, typeEmitter, (stock, type) => {
      console.log('%c getin combineSymbolCategory ==> ', 'color: #0f0')
      return {
        symbol: stock.symbol,
        annoType: type
      }
    }).scan((state, curr) => {
      if (state.symbol !== curr.symbol) {
        return {
          ...cloneDeep(rawState),
          symbol: curr.symbol,
          currentType: curr.annoType
        }
      } else {
        return {
          ...state,
          currentType: curr.annoType
        }
      }
    }, cloneDeep(rawState))
    .do(data => console.log('%c combineSymbolCategory ==> ', 'color: #0f0', data))

    let getAnnoLists = Observable.combineLatest(combineSymbolCategory, loadEmitter, (state, signal:any) => {
        console.log('%c =======>>>>>>>', 'color: #0f0', signal)
        if (signal === 'first') {
          return state
        } else if (signal.loadMore) {
          signal.loadMore = false
          state.downLoad = true
          return state
        } else {
          return state
        }
      })
      .switchMap(state => {
        let index = state.annoTypeLists.indexOf(state.currentType)
        console.log('%c index', 'color: #0f0', index)
        console.log('%c 请求数据之前的仓库状态', 'color: #0f0', state)
        if (state.downLoad && !state.annoTypeSource[index].isDone) {
          // 仅允许点击下载按钮时进入
          console.log('%c loadMore', 'color: #0f0', index)
          return loadData(state)
            .map(data => data.map(d => {
              return {
                ...d,
                infoPublDate: removeHMS(d.infoPublDate)
              }
            }))
            .map(data => {
              state.downLoad = false
              state.annoTypeSource[index].newData = data
              state.annoTypeSource[index].isDone = data.length < state.annoTypeSource[index].perPage
                ? true
                : false
              return state
            })
        } else if ( index > -1 && state.annoTypeSource[index].data.length === 0) {
          console.log('%c else if', 'color: #0f0')
          return loadData(state)
            .map(data => data.map(d => {
              return {
                ...d,
                infoPublDate: removeHMS(d.infoPublDate)
              }
            }))
            .map(data => {
              state.annoTypeSource[index].newData = data
              return state
            })
        } else {
          console.log('%c else', 'color: #0f0')
          state.downLoad = false
          state.annoTypeSource[index].newData = []
          return Observable.of(state)
        }
      })
      .do(data => console.log('%c getAnnoLists ==> ', 'color: #0f0', data))
      .scan((oldState: any, stateWithNewData: any) => {
        let index = stateWithNewData.annoTypeLists.indexOf(stateWithNewData.currentType)
        if (hasownproperty.call(oldState, 'annoTypeSource')) {
          oldState = {
            ...oldState,
            symbol: stateWithNewData.symbol,
            currentType: stateWithNewData.currentType
          }
          if (stateWithNewData.annoTypeSource[index].newData.length > 0) {
            oldState.annoTypeSource[index].data = [...oldState.annoTypeSource[index].data, ...stateWithNewData.annoTypeSource[index].newData]
            oldState.annoTypeSource[index].page = Math.floor(oldState.annoTypeSource[index].data.length / oldState.annoTypeSource[index].perPage) + 1
          }
          return oldState
        } else {
          stateWithNewData.annoTypeSource[index].data = stateWithNewData.annoTypeSource[index].newData
          stateWithNewData.annoTypeSource[index].page = Math.floor(stateWithNewData.annoTypeSource[index].data.length / stateWithNewData.annoTypeSource[index].perPage) + 1
          return stateWithNewData
        }
      }, {})

    // 返回相应类型的数据
    return getAnnoLists.map(state => {
      console.log('%c filter ===>>>>>>', 'color:#0f0', state)
      let index = state.annoTypeLists.indexOf(state.currentType)
      return state.annoTypeSource[index]
    })
    .do(data => console.log('%c ===>>>>>', 'color:#0f0', data))
  }
} 